﻿using Common.Result;
using IService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model.Dto.ShoppingCart;
using Model.Entitys;

namespace TakeawayWebApi.Controllers
{
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class ShoppingCartController : ControllerBase
    {
        private readonly ILogger<ShoppingCartController> _logger;
        private readonly IShoppingCartService _shoppingCartService;
        public ShoppingCartController(ILogger<ShoppingCartController> logger, IShoppingCartService shoppingCartService)
        {
            _logger = logger;
            _shoppingCartService = shoppingCartService;
        }
        
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="shoppingCartAdd"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<ApiResult> Add(ShoppingCartAdd shoppingCartAdd)
        {
            long userId = Convert.ToInt64(HttpContext.User.Claims.ToList()[0].Value);
            if(await _shoppingCartService.AddOrEditAsync(shoppingCartAdd, userId,false))
            {
                return ResultHelper.Success("添加购物车成功");
            }
            return ResultHelper.Error("添加购物车失败");
        }
        [HttpPost("sub")]
        public async Task<ApiResult> Sub(ShoppingCartAdd shoppingCartAdd)
        {
            long userId = Convert.ToInt64(HttpContext.User.Claims.ToList()[0].Value);
            if (await _shoppingCartService.AddOrEditAsync(shoppingCartAdd, userId, true))
            {
                return ResultHelper.Success("操作成功");
            }
            return ResultHelper.Error("操作失败");
        }
        /// <summary>
        /// 查看购物车
        /// </summary>
        [HttpGet("list")]
        public async Task<ApiResult> GetShoppingCarts()
        {
            long userId = Convert.ToInt64(HttpContext.User.Claims.ToList()[0].Value);
            return ResultHelper.Success(await _shoppingCartService.GetShoppingCartsAsync(userId)); 
        }
        /// <summary>
        /// 清空购物车
        /// </summary>
        /// <returns></returns>
        [HttpDelete("clean")]
        public async Task<ApiResult> Clean()
        {
            long userId = Convert.ToInt64(HttpContext.User.Claims.ToList()[0].Value);
            await _shoppingCartService.CleanAsync(userId);
            return ResultHelper.Success("删除购物车成功");
        }
    }
}
